import { EllipsisOutlined } from '@ant-design/icons';
import { GridContent } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Col, Dropdown, Row, Tabs, TabsProps ,DatePicker,Form, Card} from 'antd';
import type { RangePickerProps } from 'antd/es/date-picker/generatePicker';
import type { RadioChangeEvent } from 'antd/es/radio';
import dayjs from 'dayjs';
import type { FC } from 'react';
import { Suspense, useEffect, useState } from 'react';
import IntroduceRow from './components/IntroduceRow';
import Hit from './components/hit';
import PageLoading from './components/PageLoading';
import type { TimeType } from './components/SalesCard';
import TopSearch from './components/TopSearch';
import type { AnalysisData } from './data.d';
import { fakeChartData } from './service';
import useStyles from './style.style';
import { getTimeDistance } from './utils/utils';
type RangePickerValue = RangePickerProps<dayjs.Dayjs>['value'];
type AnalysisProps = {
  dashboardAndanalysis: AnalysisData;
  loading: boolean;
};
type SalesType = 'all' | 'online' | 'stores';
const { RangePicker } = DatePicker;

import { fetchHitsList, fetchPvUvList, fetchVisitRecordList ,selectTitle} from '@/services/ant-design-pro/dashboard';
import { Empty } from 'antd';

const App = () =>  {
return(  <Card
  title="PVUV访问量"
  bordered={false}
  headStyle={{ fontSize: 14,fontWeight: 400 ,color: 'rgba(0, 0, 0, 0.65)' }} 
>
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
</Card>)
  
};
const Analysis: FC<AnalysisProps> = () => {
  const { styles } = useStyles();
  const [salesType, setSalesType] = useState<SalesType>('all');
  const [currentTabKey, setCurrentTabKey] = useState<string>('');
  const [rangePickerValue, setRangePickerValue] = useState<RangePickerValue>(
   ''
  );

  // createTime:dayjs(rangePickerValue[0]).format("YYYY-MM-DD") ,endDate: dayjs(rangePickerValue[1]).format("YYYY-MM-DD") }
  const [menuType, setSelectedKeys] = useState('login');
  const { loading, data } = useRequest(fakeChartData);
  const { data: pvuvData, run: runPvUvRequest } = useRequest(() => fetchPvUvList({ menuType ,titleId:currentTabKey,startDate:rangePickerValue ? dayjs(rangePickerValue[0]).format("YYYY-MM-DD") :'' ,endDate:rangePickerValue? dayjs(rangePickerValue[1]).format("YYYY-MM-DD"):''}), {
    manual: false, // 改为自动执行
    // 添加 defaultParams 确保初始请求
    defaultParams: [{ menuType,titleId:currentTabKey }]
  });

  const { data: hitsData, run: runHitsRequest } = useRequest(() => fetchHitsList({ menuType ,titleId:currentTabKey,startDate:rangePickerValue ? dayjs(rangePickerValue[0]).format("YYYY-MM-DD") :'' ,endDate:rangePickerValue ? dayjs(rangePickerValue[1]).format("YYYY-MM-DD"):''}), {
    manual: false,
    defaultParams: [{ menuType ,titleId:currentTabKey}]
  });

  const { data: visitData, run: runVisitRequest } = useRequest(() => fetchVisitRecordList({ menuType,titleId:currentTabKey ,startDate:rangePickerValue ? dayjs(rangePickerValue[0]).format("YYYY-MM-DD") :'' ,endDate:rangePickerValue ? dayjs(rangePickerValue[1]).format("YYYY-MM-DD"):''}), {
    manual: false,
    defaultParams: [{ menuType,titleId:currentTabKey }]
  });
  const { data: titleData, run: runTitleRequest } = useRequest(() => selectTitle({ menuType }) , {
    manual: false,
    defaultParams: [{ menuType }]
  });

  const fetchData = async () => {
    try {
      const titleResponse = await runTitleRequest({ menuType: menuType });
      if (titleResponse?.length > 0) {
       await  setCurrentTabKey(titleResponse[0].key);
        console.log(titleResponse,'titleResponse')
      } else {
        console.log()
      await   setCurrentTabKey('');
      }
      // Run other requests with the updated currentTabKey  createTime:dayjs(rangePickerValue[0]).format("yyyy-mm-dd") ,endDate:dayjs(rangePickerValue[1])
      setTimeout( async () => {
        await runPvUvRequest({ menuType: menuType, titleId: currentTabKey});
        await runHitsRequest({ menuType: menuType, titleId: currentTabKey });
        await runVisitRequest({ menuType: menuType, titleId: currentTabKey});
      }, 0);

    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };


  // 监听 menuType 变化并重新请求数据
  useEffect(() => {
 
  
    fetchData();
  }, [menuType,rangePickerValue]);

  

  const onChange = async (key: string) => {
    await setSelectedKeys(key);
  };

  const items: TabsProps['items'] = [
    {
      key: 'login',
      label: '登录',
    },
    {
      key: 'register',
      label: '立即注册',
    },
    {
      key: 'index',
      label: '首页',
     
    },
    {
      key: 'menu',
      label: '导航菜单',
     
    },
    {
      key: 'solution',
      label: '解决方案',
     
    },
    {
      key: 'product',
      label: '产品',
     
    },
    {
      key: 'apis',
      label: 'API',
     
    },
    {
      key: 'about',
      label: '关于我们',
     
    },
    {
      key: 'news',
      label: '新闻中心',
     
    },
    {
      key: 'support',
      label: '支持与帮助',
    },
    {
      key: 'connect',
      label: '悬浮框（客服）',
    },
    {
      key: 'footer',
      label: '底部导航',
    },
  ];


  const selectDate = (type: TimeType) => {
    setRangePickerValue(getTimeDistance(type));
  };
  const handleRangePickerChange = (value: RangePickerValue) => {
    console.log(value,'dayjs')
    
    setRangePickerValue(value);
  };
  const isActive = (type: TimeType) => {
    if (!rangePickerValue) {
      return '';
    }
    const value = getTimeDistance(type);
    if (!value) {
      return '';
    }
    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return '';
    }
    if (
      rangePickerValue[0].isSame(value[0] as dayjs.Dayjs, 'day') &&
      rangePickerValue[1].isSame(value[1] as dayjs.Dayjs, 'day')
    ) {
      return styles.currentDate;
    }
    return '';
  };

  let salesPieData;

  if (salesType === 'all') {
    salesPieData = data?.salesTypeData;
  } else {
    salesPieData = salesType === 'online' ? data?.salesTypeDataOnline : data?.salesTypeDataOffline;
  }
  const transformData = (inputData) => {
    if(!inputData){
      return [];
    }
    return Object.entries(inputData).map(([key, value]) => {
      const year = key.slice(0, 4);
      const month = key.slice(4, 6);
      const day = key.slice(6, 8);
      const formattedDate = `${year}-${month}-${day}`;
      return { x: formattedDate, y: value };
    });
  }

  const transformDataKey = (inputData) => {
    if(!inputData){
      return [];
    }
    return Object.entries(inputData).map(([key, value]) => {

      return { title: key, value: value };
    })
  }

  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    console.log('Success:', values);
  };
  
  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  const activeKey = currentTabKey || (data?.offlineData[0] && data?.offlineData[0].name) || '';

  const changeCurrentKey = async (key) => {
  
   await setCurrentTabKey(key);
   await runPvUvRequest({ menuType: menuType, titleId: currentTabKey });
   await runHitsRequest({ menuType: menuType, titleId: currentTabKey });
   await runVisitRequest({ menuType: menuType, titleId: currentTabKey });
  };
  return (
    <><Form
      name="basic"
      initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item name={'栏目'} >
      <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
      </Form.Item>
      <Form.Item name={'时间'} label='时间'>
      <RangePicker value={rangePickerValue} onChange={handleRangePickerChange} />
      </Form.Item>
     
    </Form><>
    
    <GridContent>

      <>
      <Tabs defaultActiveKey={currentTabKey} onChange={changeCurrentKey} items={titleData} key={currentTabKey} ></Tabs>
      <Suspense fallback={<PageLoading />}>
        {<Hit loading={loading} visitData={( hitsData?.resultVoList ? hitsData?.resultVoList[0].resultVo2List : []) || []}  />}
        </Suspense>
        <Suspense  style={ {backgroundColor:'#fff'} } fallback={<PageLoading />}>
          {pvuvData?.resultVoList ?  <IntroduceRow loading={loading} visitData1={transformData(pvuvData?.resultVoList ? pvuvData?.resultVoList[0].pvMap : []) || []}  visitData2={transformData( pvuvData?.resultVoList ? pvuvData?.resultVoList[0].uvMap:[]) || []}  /> : <App/>}
        </Suspense>
        <Row
          gutter={24}
          style={{
            marginTop: 24,
          }}
        >
          <Col xl={24} lg={24} md={24} sm={24} xs={24}>
<Suspense fallback={null}>
{  <TopSearch
    loading={loading}
    searchData={visitData?.visitRecordList || []}
  />}
</Suspense>
</Col>

        </Row>


      </>
    </GridContent></></>
  );
};
export default Analysis;
